<?php
/**
 * Created by PhpStorm.
 * User: 17274
 * Date: 2018/3/27
 * Time: 21:06
 */
namespace app\admin\model\image_video;

use app\admin\helper\DBhelper;
use app\admin\helper\LangHelper;
use app\admin\helper\SearchHelper;
use app\admin\model\BaseM;
use app\admin\model\LogsM;
use app\admin\popo\LayData;
use think\Config;
use think\Session;
use think\Validate;

class ArticleM extends  BaseM
{
    protected $table = 'tb_article';
    protected $module = '文章列表';

    /*
     * rule
     * 验证data
     * @params $data
     * 新增和修改时验证
     * */
    public function validate_model(){
        $post = input('post.');
        $rule = [
            'title' => 'require',
            'sub_title' => 'require',
            'content' => 'require',
            'tag' => 'alpha',
        ];
        $msg = [
            'title.require' => '__validata.title.require__',
            'sub_title.require' => '__validata.sub_title.require__',
            'content.require' => '__validata.content.require__',
            'tag.alpha' => '__tag.validata.code.alpha__',
        ];
        $msg = LangHelper::convertLang($msg,'field');
        $validate = new Validate($rule, $msg);
        $result = $validate->check($post);
        if(!$result){
            return op_msg(0,$validate->getError());
        }
        return op_msg(1,'success');
    }

    /**
     * 前端search控件
     * button vale [ add edit del search export ]
     * @return mixed
     */
    public function __search(){
        $search = [
            'tag'=>['field'=>'tag','title'=>'__tag__','type'=>'input','value'=>''],
            'status'=>['field'=>'status','title'=>'__status__','type'=>'select','value'=>'function:getStatusList'],
            'tags'=>['field'=>'tags','title'=>'__tags__','type'=>'select','value'=>'function:getTagList'],
            'created_at'=>['field'=>'created_at','title'=>'__created_at__','type'=>'date_range','value'=>'function:getMonthDateRange'],
            'button'=>['type'=>'button','value'=>['add','search','export']],
        ];
        SearchHelper::convertValue($search);
        $search['form'] = implode(',',array_keys($search));
        return LangHelper::convertLang($search,'field');
    }

    /**
     * 前端表格列
     * @return string
     */
    public function __header(){
        $header = [
            ['type'=>'checkbox'],
            ['field'=>'title','title'=>'__title__'],
            ['field'=>'sub_title','title'=>'__sub_title__'],
            ['field'=>'hits','title'=>'__hits__'],
            ['field'=>'likes','title'=>'__likes__'],
            ['field'=>'label','title'=>'__label__'],
            ['field'=>'tag_name','title'=>'__tags__'],
            ['field'=>'status','title'=>'__status__'],
            ['field'=>'created_at','title'=>'__created_at__'],
            ['field'=>'updated_at','title'=>'__updated_at__'],
            ['field'=>'op','title'=>'__op__','toolbar'=>'#operate']
        ];
        return json_encode(LangHelper::convertLang($header,'field'));
    }

    /*
     * 列表
     * */
    public function listData(){
        $page=input("post.page/d");
        $limit=input("post.limit/d");
        $tag=input("post.tag/s");
        $time=input("post.created_at/s");
        $start = strtotime(explode(' - ',$time)[0]);
        $end = strtotime(explode(' - ',$time)[1]);

        $where = [
            'a.title|a.sub_title|a.content|b.name|b.code'=>['like',"%".$tag."%"],
            'a.created_at'=>['between', [$start, $end+86399]]
        ];
        $status=input("post.status/d");
        if ($status>0) {
            $where['a.status'] = $status;
        }

        $tags=input("post.tags/s");
        if (!empty($tags)) {
            $where['a.tag'] = $tags;
        }

        $log = [
            'op_uid' => Session::get('username'),
            'op_module' => $this->module,
            'op_type' => 'search',
            'op_origin' => $this->table,
            'op_data' => json_encode($where,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
            'op_ip' => getIP(),
        ];
        //export逻辑
        if (input("post.export/b")) {
            $header = json_decode($this->__header(),true);
            $export_data = $this->alias('a')->field('a.*,b.name tag_name,count(c.realtion_id) likes')
                    ->join('tb_tag b','a.tag = b.code','left')
                ->join('tb_like c',"a.id = c.realtion_id and c.tag='article'",'left')
                ->where($where)->group('a.id')->order('id desc')->select();
            $log['op_sql'] = $this->getLastSql();
            $log['op_type'] = 'export';
            $log['op_data'] = json_encode($header,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
            LogsM::add($log);
            pr_log($log,'operate');
            export('文章列表',$export_data->toArray(),$header);
        }

        $resp = new LayData();
        $resp->count = $this->alias('a')->field('a.*,b.name tag_name')
            ->join('tb_tag b','a.tag = b.code','left')
            ->where($where)->count();
        $resp->data = $this->alias('a')->field('a.*,b.name tag_name,count(c.realtion_id) likes')
            ->join('tb_tag b','a.tag = b.code','left')
            ->join('tb_like c',"a.id = c.realtion_id and c.tag='article'",'left')
            ->where($where)->group('a.id')
            ->order('id desc')->page($page,$limit)->select();
        $resp->extra_data = Config::get('app_debug')?$this->getLastSql():'';
        $log['op_sql'] = $this->getLastSql();
        LogsM::add($log);
        pr_log($log,'operate');
        return $resp;
    }

    /*
     * 新增
     * */
    public function add(){
        $data=input('post.');
        unset($data['method']);
        $data['created_at']=time();
        $data['updated_at']=time();
        $re = $this->save($data);
        $last_sql = "";
        if($re){
            $log = [
                'op_uid' => Session::get('username'),
                'op_module' => $this->module,
                'op_type' => 'add',
                'op_origin' => $this->table,
                'op_data' => $data['title'],
                'op_ip' => getIP(),
                'op_sql' => "",
            ];
            LogsM::add($log);
            pr_log($log,'operate');
            return op_success($last_sql);
        }
        return op_fail($last_sql);
    }

    /*
     * 修改
     * */
    public function edit(){
        $data=input('post.');
        $id=$data['id'];
        unset($data['method']);
        //只修改变化字段
        $origin = $this->getById($id)->toArray();
        $data = DBhelper::getChangeData($data,$origin);
        if (!empty($data)){
            $data['updated_at']=time();
            $re = $this->where('id',$id)->update($data);
            $last_sql = "";
            if($re){
                unset($data['content']);
                $data['title'] = $origin['title'];
                $log = [
                    'op_uid' => Session::get('username'),
                    'op_module' => $this->module,
                    'op_type' => 'edit',
                    'op_origin' => $this->table,
                    'op_data' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                    'op_ip' => getIP(),
                    'op_sql' => "",
                ];
                LogsM::add($log);
                pr_log($log,'operate');
                return op_success($last_sql);
            }
            return op_fail($last_sql);
        }
        return op_nochange();
    }

    /*
     * 删除
     * */
    public function del(){
        $ids=input('post.ids/a');
        $op_name=[];
        foreach ($ids as $id){
            $name = $this->getById($id)->toArray()['title'];
            array_push($op_name,$name);
        }
        if (!empty($op_name)) {
            $re = $this->destroy($ids);
            $last_sql = Config::get('app_debug')?self::getLastSql():'';
            if ($re){
                $log = [
                    'op_uid' => Session::get('username'),
                    'op_module' => $this->module,
                    'op_type' => 'delete',
                    'op_origin' => $this->table,
                    'op_data' => json_encode($op_name,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                    'op_ip' => getIP(),
                    'op_sql' => $this->getLastSql(),
                ];
                LogsM::add($log);
                pr_log($log,'operate');
                return op_success($last_sql);
            }
            return op_fail($last_sql);
        }
        return op_superadmin();
    }

}